<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT">










<meta name="description" content="神经网络初探声明：本教程使用PyTorch&amp;gt;=1.3和Fastai v1以上版本。原教程来自Jeremy Howard，因其为全英文，同时笔者在自学过程中记了一些笔记，本着分离的精神遂将笔记分享。须知原作者为Jeremy Howard。 MNIST数据集设置我们使用黑白手写数字数据集MNIST，其包含70000张从0到9的手写数字图片，图像尺寸为28*28像素。 12345678910111">
<meta property="og:type" content="article">
<meta property="og:title" content="001a_神经网络_基础">
<meta property="og:url" content="http://yoursite.com/2020/01/17/001a-神经网络-基础/index.html">
<meta property="og:site_name" content="林晗的AI笔记">
<meta property="og:description" content="神经网络初探声明：本教程使用PyTorch&amp;gt;=1.3和Fastai v1以上版本。原教程来自Jeremy Howard，因其为全英文，同时笔者在自学过程中记了一些笔记，本着分离的精神遂将笔记分享。须知原作者为Jeremy Howard。 MNIST数据集设置我们使用黑白手写数字数据集MNIST，其包含70000张从0到9的手写数字图片，图像尺寸为28*28像素。 12345678910111">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://linha-image.oss-ap-southeast-2.aliyuncs.com/mnist_sample.png">
<meta property="og:updated_time" content="2020-01-17T12:51:02.164Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="001a_神经网络_基础">
<meta name="twitter:description" content="神经网络初探声明：本教程使用PyTorch&amp;gt;=1.3和Fastai v1以上版本。原教程来自Jeremy Howard，因其为全英文，同时笔者在自学过程中记了一些笔记，本着分离的精神遂将笔记分享。须知原作者为Jeremy Howard。 MNIST数据集设置我们使用黑白手写数字数据集MNIST，其包含70000张从0到9的手写数字图片，图像尺寸为28*28像素。 12345678910111">
<meta name="twitter:image" content="https://linha-image.oss-ap-southeast-2.aliyuncs.com/mnist_sample.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2020/01/17/001a-神经网络-基础/">





  <title>001a_神经网络_基础 | 林晗的AI笔记</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?5dc2336546289f1a7e5a6ac3dbfab34a";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">林晗的AI笔记</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/01/17/001a-神经网络-基础/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="南林笑笑生">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="林晗的AI笔记">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">001a_神经网络_基础</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-01-17T20:46:05+08:00">
                2020-01-17
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="神经网络初探"><a href="#神经网络初探" class="headerlink" title="神经网络初探"></a>神经网络初探</h1><p>声明：本教程使用PyTorch&gt;=1.3和Fastai v1以上版本。原教程来自Jeremy Howard，因其为全英文，同时笔者在自学过程中记了一些笔记，本着分离的精神遂将笔记分享。须知原作者为Jeremy Howard。</p>
<h2 id="MNIST数据集设置"><a href="#MNIST数据集设置" class="headerlink" title="MNIST数据集设置"></a>MNIST数据集设置</h2><p>我们使用黑白手写数字数据集MNIST，其包含70000张从0到9的手写数字图片，图像尺寸为28*28像素。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> pathlib <span class="keyword">import</span> Path</span><br><span class="line"><span class="keyword">import</span> requests</span><br><span class="line"></span><br><span class="line">DATA_PATH = Path(<span class="string">'data'</span>)</span><br><span class="line">PATH = DATA_PATH/<span class="string">'mnist'</span></span><br><span class="line"></span><br><span class="line">PATH.mkdir(parents=<span class="literal">True</span>, exist_ok=<span class="literal">True</span>)</span><br><span class="line"></span><br><span class="line">URL=<span class="string">'http://deeplearning.net/data/mnist/'</span></span><br><span class="line">FILENAME=<span class="string">'mnist.pkl.gz'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> <span class="keyword">not</span> (PATH/FILENAME).exists():</span><br><span class="line">    content = requests.get(URL+FILENAME).content</span><br><span class="line">    (PATH/FILENAME).open(<span class="string">'wb'</span>).write(content)</span><br></pre></td></tr></table></figure>

<p>数据集是numpy数组格式，已经使用pickle序列化了，这里把它们导入内存的时候要反序列化。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> pickle, gzip</span><br><span class="line"></span><br><span class="line"><span class="keyword">with</span> gzip.open(PATH/FILENAME, <span class="string">'rb'</span>) <span class="keyword">as</span> f:</span><br><span class="line">    ((x_train, y_train), (x_valid, y_valid), _) = \</span><br><span class="line">        pickle.load(f, encoding=<span class="string">'latin-1'</span>)</span><br></pre></td></tr></table></figure>

<p>每个图像大小为28x28，并被存储为长度为784 (=28x28)的向量而非矩阵。我们来看一眼：我们需要先将其重塑为二维数组。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">%matplotlib inline</span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> matplotlib <span class="keyword">import</span> pyplot</span><br><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"></span><br><span class="line">pyplot.imshow(x_train[<span class="number">0</span>].reshape((<span class="number">28</span>,<span class="number">28</span>)), cmap=<span class="string">"gray"</span>)</span><br><span class="line">x_train.shape</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">(50000, 784)</span><br><span class="line">&lt;class &apos;numpy.ndarray&apos;&gt;</span><br></pre></td></tr></table></figure>

<p><img src="https://linha-image.oss-ap-southeast-2.aliyuncs.com/mnist_sample.png" alt="image"><br>PyTorch使用的数组格式是torch.tensor而非numpy数组，因此我们需要转化一下数据格式。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> torch </span><br><span class="line"></span><br><span class="line">x_train,y_train,x_valid,y_valid = map(torch.tensor, \</span><br><span class="line">    (x_train,y_train,x_valid,y_valid))</span><br><span class="line">n,c = x_train.shape</span><br><span class="line">x_train, x_train.shape, y_train.min(), y_train.max()</span><br></pre></td></tr></table></figure>

<hr>
## 完全手撸的神经网络（不用torch.nn模块）
让我们先用PyTorch张量运算建立一个模型。我们假设你已经熟悉了神经网络的基础知识。(如果你没有，你可以在fast.ai课程中学习一下。)
PyTorch提供了创建随机或零填充张量的方法，我们将使用这些方法创建一个简单线性模型的权重和偏差。这些只是普通的张量，有一个非常特殊的添加:我们告诉PyTorch它们需要一个梯度。这使得PyTorch记录了对张量做的所有操作，这样它就可以自动计算反向传播过程中的梯度了!
对于权重，我们在初始化之后设置requires_grad，因为我们不希望该步骤包含在梯度中。(注意，在PyTorch中标记_表示操作是执行后赋值回去。)
注:我们在这里初始化的权重与Xavier初始化(乘以`$\dfrac{1}{\sqrt{n}}$`)。
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> math</span><br><span class="line"></span><br><span class="line">weights = torch.randn(<span class="number">784</span>,<span class="number">10</span>)/math.sqrt(<span class="number">784</span>)</span><br><span class="line">weights.requires_grad_()</span><br><span class="line">bias = torch.zeros(<span class="number">10</span>, requires_grad=<span class="literal">True</span>)</span><br></pre></td></tr></table></figure>

<p>由于PyTorch能够自动计算梯度，我们可以使用任何标准的Python函数(或可调用对象)作为模型！让我们写一个简单的矩阵乘法并加入加法来创建一个简单的线性模型。我们还需要一个激活函数，因此我们将编写log_softmax并使用它。请记住:虽然PyTorch提供了许多预先编写的损失函数、激活函数等，但是您可以使用普通python轻松地编写自己的函数。PyTorch甚至可以为你的函数自动创建快速的GPU或矢量化的CPU代码。<br>​<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 损失函数</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">log_softmax</span><span class="params">(x)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> x - x.exp().sum(<span class="number">-1</span>).log().unsqueeze(<span class="number">-1</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 前面传播</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">model</span><span class="params">(xb)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> log_softmax(xb @ weights + bias)</span><br></pre></td></tr></table></figure></p>
<p>在上面，“@”代表点积操作。我们将对一批数据(在本例中为64张图像)调用函数。这是一次向前传播。注意，我们的预测在这个阶段未必比随机的好，因为我们从随机的权值开始。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">bs=<span class="number">64</span>                  <span class="comment"># batch size</span></span><br><span class="line"></span><br><span class="line">xb = x_train[<span class="number">0</span>:bs]     <span class="comment"># a mini-batch from x</span></span><br><span class="line">preds = model(xb)      <span class="comment"># predictions</span></span><br><span class="line">preds[<span class="number">0</span>], preds.shape</span><br></pre></td></tr></table></figure>

<p>正如你所看到的，preds张量不仅包含张量值，还包含一个梯度。我们稍后会用它来做反向传播（back propagation）。<br>让我们实现负对数似然函数作为损失函数(同样，我们可以使用标准的Python):</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">nll</span><span class="params">(input, target)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> -input[range(target.shape[<span class="number">0</span>]), target].mean()</span><br><span class="line"></span><br><span class="line">loss_func = nll</span><br></pre></td></tr></table></figure>

<p>让我们用我们的随机模型来检查一下我们的损失，这样我们就可以看到我们是否会在反向传播后有所改善。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">yb = y_train[<span class="number">0</span>:bs]</span><br><span class="line"></span><br><span class="line"><span class="comment"># 用负对数似然函数衡量的损失</span></span><br><span class="line">loss_func(preds, yb)</span><br></pre></td></tr></table></figure>

<p>让我们实现一个函数来计算我们的模型的精度。对于每个预测，如果具有最大值的索引与目标值匹配，则预测是正确的。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">accuracy</span><span class="params">(out, yb)</span>:</span></span><br><span class="line">    preds = torch.argmax(out, dim=<span class="number">1</span>)</span><br><span class="line">    <span class="keyword">return</span> (preds==yb).float().mean()</span><br></pre></td></tr></table></figure>

<p>让我们检查一下随机模型的准确性，这样我们就可以看到我们的准确性是否会随着损失的增加而提高。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">accuracy(preds, yb)</span><br></pre></td></tr></table></figure>

<p>我们现在可以运行一个训练循环。对于每个迭代，我们将:</p>
<ul>
<li>选择一小批数据(大小为bs)</li>
<li>使用模型进行预测</li>
<li>计算损失</li>
<li>loss.backward()更新模型的梯度（在本例中更新的是权重和偏差的梯度）。</li>
<li>我们现在使用这些梯度来更新权重和偏差。我们在torch.no_grad()上下文管理器中执行此操作，因为我们不希望在下一次计算梯度时记录这些操作。</li>
<li>然后，我们将梯度设置为零，以便为下一个循环做好准备。否则，我们的梯度将记录所有已经发生的操作的运行记录(例如，loss. backwards()将梯度添加到已经存储的内容中，而不是替换它们)，这样的话下次更新参数就使用了错误的梯度了。<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> IPython.core.debugger <span class="keyword">import</span> set_trace</span><br><span class="line"></span><br><span class="line">lr = <span class="number">0.5</span>   <span class="comment"># learning rate</span></span><br><span class="line">epochs = <span class="number">2</span> <span class="comment"># how many epochs to train for</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> epoch <span class="keyword">in</span> range(epochs):</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range((n<span class="number">-1</span>)//bs + <span class="number">1</span>):</span><br><span class="line"><span class="comment">#         set_trace()</span></span><br><span class="line">        start_i = i*bs</span><br><span class="line">        end_i = start_i+bs</span><br><span class="line">        xb = x_train[start_i:end_i]</span><br><span class="line">        yb = y_train[start_i:end_i]</span><br><span class="line">        pred = model(xb)</span><br><span class="line">        loss = loss_func(pred, yb)</span><br><span class="line"></span><br><span class="line">        loss.backward()</span><br><span class="line">        <span class="keyword">with</span> torch.no_grad():</span><br><span class="line">            weights -= weights.grad * lr</span><br><span class="line">            bias -= bias.grad * lr</span><br><span class="line">            weights.grad.zero_()</span><br><span class="line">            bias.grad.zero_()</span><br></pre></td></tr></table></figure>

</li>
</ul>
<p>好了:我们已经完全从零开始创建并训练了一个最小的神经网络(在本例中是逻辑回归，因为我们没有隐藏层)!<br>让我们检查一下损失和准确性，并与我们之前得到的进行比较。我们预计损失会减少，准确性会提高，他们确实做到了。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">loss_func(model(xb), yb), accuracy(model(xb), yb)</span><br></pre></td></tr></table></figure>

<hr>
## 使用torch.nn.functional
现在我们将重构我们的代码，使它做与以前相同的事情，只是我们将开始利用PyTorch的nn类使它更简洁和灵活。从这里开始的每一步，我们都应该使我们的代码变得更短、更容易理解和/或更灵活。
第一步，也是最简单的一步，是将我们手写的激活函数和损失函数替换为来自于torch.nn.functional的函数(通常按照惯例导入后临时命名为F)，从而缩短代码。。这个模块包含了torch.nn库中的所有函数(而库的其他部分包含类)。除了各种各样的损失和激活函数之外，您还可以在这里找到一些用于创建神经网络的方便函数，比如池函数(pooling)。(也有一些函数用于执行卷积、线性层等，但是我们将看到，使用库的其他部分通常可以更好地处理这些函数。)
如果您使用的是负对数似然损失和对数softmax激活，那么Pytorch提供了一个单独的函数F.cross_entropy两者结合起来，即交叉熵。因此我们甚至可以从现在的模型中移除激活函数了。
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> torch.nn.functional <span class="keyword">as</span> F</span><br><span class="line">loss_func = F.cross_entropy</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">model</span><span class="params">(xb)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> xb @ weights + bias</span><br></pre></td></tr></table></figure>

<p>注意，我们不再在模型函数中调用log_softmax。我们确认一下我们的损失和准确性和之前一样:<br>​<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">loss_func(model(xb), yb), accuracy(model(xb), yb)</span><br></pre></td></tr></table></figure></p>
<hr>
## 使用nn.Module重构
接下来，我们将使用nn.Module和nn.Parameter进行更清晰，更简洁的训练循环。 我们将从nn.Module（它本身是一个类并且能够跟踪状态）继承并创建它的子类。在本例中，我们要创建一个类，该类包含前向传播的weights, bias和前向传播的函数。nn.Module具有许多我们将要使用的属性和方法（例如.parameters（）和.zero_grad（））。

<p>注意：nn.Module（大写M）是PyTorch的特定概念，并且是我们将大量使用的类。 nn.Module不要与Python的module概念混淆，该概念是可以导入的Python代码文件。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> torch <span class="keyword">import</span> nn</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Mnist_Logistic</span><span class="params">(nn.Module)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        super().__init__()</span><br><span class="line">        self.weights = nn.Parameter(torch.randn(<span class="number">784</span>,<span class="number">10</span>)/\</span><br><span class="line">            math.sqrt(<span class="number">784</span>))</span><br><span class="line">        self.bias = nn.Parameter(torch.zeros(<span class="number">10</span>))</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">forward</span><span class="params">(self, xb)</span>:</span> <span class="keyword">return</span> xb @ self.weights + self.bias</span><br></pre></td></tr></table></figure>

<p>因为我们现在使用的是对象而不是函数，我们首先要实例化我们的模型:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">model = Mnist_Logistic()</span><br></pre></td></tr></table></figure>

<p>有意思的是，nn.Module()这个类里实现了<strong>call</strong>()这个方法，因此这个类实例出来的对象是可调用的（本博客内的文章有详细介绍），因此接下来我们可以直接把model作为函数来调用。<br>现在我们可以用以前的方法来计算损失。注意,nn.Module对象被当作函数来使用（但是在后台Pytorch会自动调用我们的forward方法）。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">loss_func(model(xb), yb)</span><br></pre></td></tr></table></figure>

<p>在之前的训练循环中，我们必须按名称更新每个参数的值，并手动将每个参数的梯度归零，如下所示:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">with</span> torch.no_grad():</span><br><span class="line">    weights -= weights.grad * lr</span><br><span class="line">    bias -= bias.grad * lr</span><br><span class="line">    weights.grad.zero_()</span><br><span class="line">    bias.grad.zero_()</span><br></pre></td></tr></table></figure>

<p>现在，我们可以利用model.parameters()和model.zero_grad()(它们都是由PyTorch为n. module定义的)来简化这些步骤，减少忘记一些参数的错误，特别是当我们有一个更复杂的模型时:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">with</span> torch.no_grad():</span><br><span class="line">    <span class="keyword">for</span> p <span class="keyword">in</span> model.parameters(): p -= p.grad * lr</span><br><span class="line">    model.zero_grad()</span><br></pre></td></tr></table></figure>

<p>我们将在’fit’函数中封装我们的训练循环，以便稍后再次运行它。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">fit</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="keyword">for</span> epoch <span class="keyword">in</span> range(epochs):</span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> range((n<span class="number">-1</span>)//bs + <span class="number">1</span>):</span><br><span class="line">            start_i = i*bs</span><br><span class="line">            end_i = start_i+bs</span><br><span class="line">            xb = x_train[start_i:end_i]</span><br><span class="line">            yb = y_train[start_i:end_i]</span><br><span class="line">            pred = model(xb)</span><br><span class="line">            loss = loss_func(pred, yb)</span><br><span class="line"></span><br><span class="line">            loss.backward()</span><br><span class="line">            <span class="keyword">with</span> torch.no_grad():</span><br><span class="line">                <span class="keyword">for</span> p <span class="keyword">in</span> model.parameters(): p -= p.grad * lr</span><br><span class="line">                model.zero_grad()</span><br><span class="line"></span><br><span class="line">fit()</span><br></pre></td></tr></table></figure>

<p>让我们再次检查一下我们的损失是否减少了:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">loss_func(model(xb), yb)</span><br></pre></td></tr></table></figure>

<hr>
## 使用nn.Linear重构
我们继续重构代码。而不是手动定义和初始化参数再手动运算。我们将使用Pytorch的类nn.Linear类来代替。一个线性层的线性，它为我们做了所有这些。Pytorch有许多类型的预定义层，这些层可以极大地简化我们的代码，并且常常使它更快。
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Mnist_Logistic</span><span class="params">(nn.Module)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        super().__init__()</span><br><span class="line">        self.lin = nn.Linear(<span class="number">784</span>,<span class="number">10</span>)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">forward</span><span class="params">(self, xb)</span>:</span> <span class="keyword">return</span> self.lin(xb)</span><br></pre></td></tr></table></figure>

<p>我们实例化我们的模型，并按照与之前相同的方式计算损失:<br>​<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">model = Mnist_Logistic()</span><br><span class="line">loss_func(model(xb), yb)</span><br></pre></td></tr></table></figure></p>
<p>然后运行一遍fit()函数来训练模型。最后对比一下损失。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">fit()</span><br><span class="line">loss_func(model(xb), yb)</span><br></pre></td></tr></table></figure>

<h2 id="使用optim重构"><a href="#使用optim重构" class="headerlink" title="使用optim重构"></a>使用optim重构</h2><p>Pytorch还有一个包含各种优化算法的包，torch.optim。我们可以使用来自优化器的step()方法来执行前向传播，而不是手动更新每个参数。<br>这将让我们取代之前的手动编码优化步骤:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">with</span> torch.no_grad():</span><br><span class="line">    <span class="keyword">for</span> p <span class="keyword">in</span> model.parameters(): p -= p.grad * lr</span><br><span class="line">    model.zero_grad()</span><br></pre></td></tr></table></figure>

<p>而是使用以下代码：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">opt.step()</span><br><span class="line">opt.zero_grad()</span><br></pre></td></tr></table></figure>

<p>(optim.zero_grad()将梯度重置为0，我们需要在为下一个minibatch计算梯度之前调用它)。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> torch <span class="keyword">import</span> optim</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">get_model</span><span class="params">()</span>:</span></span><br><span class="line">    model = Mnist_Logistic()</span><br><span class="line">    <span class="keyword">return</span> model, optim.SGD(model.parameters(), lr=lr)</span><br><span class="line">    </span><br><span class="line">model,opt = get_model()</span><br><span class="line">loss_func(model(xb), yb)</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> epoch <span class="keyword">in</span> range(epochs):</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range((n<span class="number">-1</span>)//bs + <span class="number">1</span>):</span><br><span class="line">        start_i = i*bs</span><br><span class="line">        end_i = start_i+bs</span><br><span class="line">        xb = x_train[start_i:end_i]</span><br><span class="line">        yb = y_train[start_i:end_i]</span><br><span class="line">        pred = model(xb)</span><br><span class="line">        loss = loss_func(pred, yb)</span><br><span class="line"></span><br><span class="line">        loss.backward()</span><br><span class="line">        opt.step()</span><br><span class="line">        opt.zero_grad()</span><br><span class="line"></span><br><span class="line">loss_func(model(xb), yb)</span><br></pre></td></tr></table></figure>

<hr>
## 使用Dataset重构
PyTorch有一个抽象的数据集类Dataset。一个Dataset可以是任何具有一个__len__方法(有了它就可以被Python的标准len函数调用)和一个__getitem__方法(有了它就可索引)的类。本教程将介绍一个创建自定义FacialLandmarkDataset类作为Dataset子类的示例。
PyTorch的TensorDataset是一个包装张量的数据集。通过定义长度和索引的方式，这也给了我们一种方法来遍历、索引和切片一个张量的第一维。这将使我们更容易地同时访问解释变量和被解释变量。
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> torch.utils.data <span class="keyword">import</span> TensorDataset</span><br><span class="line"></span><br><span class="line"><span class="string">'''x_train和y_train都可以组合在一个单独的TensorDataset中，</span></span><br><span class="line"><span class="string">这样更容易遍历和切片。'''</span></span><br><span class="line">train_ds = TensorDataset(x_train, y_train)</span><br></pre></td></tr></table></figure>

<p>之前，我们必须分别迭代x和y值的小批量:<br>​<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">xb = x_train [start_i end_i):</span><br><span class="line">yb = y_train [start_i end_i):</span><br></pre></td></tr></table></figure></p>
<p>现在，我们可以一起做这两个步骤:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">xb,yb = train_ds[i*bs: i*bs+bs]</span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">model,opt = get_model()</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> epoch <span class="keyword">in</span> range(epochs):</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range((n<span class="number">-1</span>)//bs + <span class="number">1</span>):</span><br><span class="line">        xb,yb = train_ds[i*bs : i*bs+bs]</span><br><span class="line">        pred = model(xb)</span><br><span class="line">        loss = loss_func(pred, yb)</span><br><span class="line"></span><br><span class="line">        loss.backward()</span><br><span class="line">        opt.step()</span><br><span class="line">        opt.zero_grad()</span><br><span class="line"></span><br><span class="line">loss_func(model(xb), yb)</span><br></pre></td></tr></table></figure>

<p>有点意思，对吧？一步一步来。</p>
<h2 id="使用DataLoader来重构"><a href="#使用DataLoader来重构" class="headerlink" title="使用DataLoader来重构"></a>使用DataLoader来重构</h2><p>Pytorch的DataLoader负责管理batches。你可以从任何数据集创建DataLoader。DataLoader简化了对batches的迭代。而不是必须使用<code>$train_ds[i * bs: i * bs+bs]$</code>， DataLoader自动为我们提供每个mini batch批处理。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> torch.utils.data <span class="keyword">import</span> DataLoader</span><br><span class="line"></span><br><span class="line">train_ds = TensorDataset(x_train, y_train)</span><br><span class="line">train_dl = DataLoader(train_ds, batch_size=bs)</span><br><span class="line"></span><br><span class="line">model,opt = get_model()</span><br><span class="line"><span class="keyword">for</span> epoch <span class="keyword">in</span> range(epochs):</span><br><span class="line">    <span class="keyword">for</span> xb,yb <span class="keyword">in</span> train_dl:</span><br><span class="line">        pred = model(xb)</span><br><span class="line">        loss = loss_func(pred, yb)</span><br><span class="line"></span><br><span class="line">        loss.backward()</span><br><span class="line">        opt.step()</span><br><span class="line">        opt.zero_grad()</span><br></pre></td></tr></table></figure>

<p>多亏了Pytorch的 nn.Module, nn.Parameter, Dataset, and DataLoader，我们的训练循环现在大大缩小，更容易理解。现在让我们尝试添加现实中创建有效模型所需的基本特性。</p>
<hr>
# 添加验证集
在第1部分中，我们只是试图建立一个合理的训练循环，以用于我们的训练数据。实际上，你总是应该有一个验证集，以便确定是否进行了过度拟合。
对训练数据进行顺序洗牌对于防止批量之间的相关性和过度拟合非常重要。另一方面，无论是否重新洗牌验证集，验证损失都是相同的。由于重新洗牌需要额外的时间，因此没有必要重新洗牌验证数据。
我们将为验证集使用两倍于训练集的批处理大小。这是因为验证集不需要反向传播，因此占用的内存更少(它不需要存储梯度)。我们利用这一点来使用更大的批大小以便更快地计算损失。
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">train_ds = TensorDataset(x_train, y_train)</span><br><span class="line">train_dl = DataLoader(train_ds, batch_size=bs, shuffle=<span class="literal">True</span>)</span><br><span class="line"></span><br><span class="line">valid_ds = TensorDataset(x_valid, y_valid)</span><br><span class="line">valid_dl = DataLoader(valid_ds, batch_size=bs*<span class="number">2</span>)</span><br></pre></td></tr></table></figure>

<p>我们将在每个epoch结束时计算并打印验证损失。<br>(注意，我们总是在训练之前调用model.train()，在推断之前调用model.eval()，因为这些是由nn.BatchNorm2d 和 nn.Dropout，以确保为这些不同的阶段采取适当的行为，比如是否有dropout，是否shuffle。)<br>​<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">model,opt = get_model()</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> epoch <span class="keyword">in</span> range(epochs):</span><br><span class="line">    model.train()</span><br><span class="line">    <span class="keyword">for</span> xb,yb <span class="keyword">in</span> train_dl:</span><br><span class="line">        pred = model(xb)</span><br><span class="line">        loss = loss_func(pred, yb)</span><br><span class="line"></span><br><span class="line">        loss.backward()</span><br><span class="line">        opt.step()</span><br><span class="line">        opt.zero_grad()</span><br><span class="line">        </span><br><span class="line">    model.eval()</span><br><span class="line">    <span class="keyword">with</span> torch.no_grad():</span><br><span class="line">        valid_loss = sum(loss_func(model(xb), yb)</span><br><span class="line">                         <span class="keyword">for</span> xb,yb <span class="keyword">in</span> valid_dl)</span><br><span class="line"></span><br><span class="line">    print(epoch, valid_loss/len(valid_dl))</span><br></pre></td></tr></table></figure></p>
<h2 id="重构一下拟合和获取数据的代码"><a href="#重构一下拟合和获取数据的代码" class="headerlink" title="重构一下拟合和获取数据的代码"></a>重构一下拟合和获取数据的代码</h2><p>现在我们自己来做一点重构。因为我们要经历一个类似的过程，两次计算训练集和验证集的损失，所以让我们将其转换为自己的函数“loss_batch”，它计算一个批处理的损失。<br>我们为训练集传递一个优化器，并使用它来执行backprop。对于验证集，我们不传递优化器，因此该方法不执行backprop。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">loss_batch</span><span class="params">(model, loss_func, xb, yb, opt=None)</span>:</span></span><br><span class="line">    loss = loss_func(model(xb), yb)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> opt <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span>:</span><br><span class="line">        loss.backward()</span><br><span class="line">        opt.step()</span><br><span class="line">        opt.zero_grad()</span><br><span class="line">        </span><br><span class="line">    <span class="keyword">return</span> loss.item(), len(xb)</span><br></pre></td></tr></table></figure>

<p>定义fit()函数运行必要的操作来训练我们的模型，并计算每个epoch的训练和验证损失。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">fit</span><span class="params">(epochs, model, loss_func, opt, train_dl, valid_dl)</span>:</span></span><br><span class="line">    <span class="keyword">for</span> epoch <span class="keyword">in</span> range(epochs):</span><br><span class="line">        model.train()</span><br><span class="line">        <span class="keyword">for</span> xb,yb <span class="keyword">in</span> train_dl: loss_batch(model, loss_func, xb, yb, opt)</span><br><span class="line"></span><br><span class="line">        model.eval()</span><br><span class="line">        <span class="keyword">with</span> torch.no_grad():</span><br><span class="line">            losses,nums = zip(*[loss_batch(model, loss_func, xb, yb)</span><br><span class="line">                                <span class="keyword">for</span> xb,yb <span class="keyword">in</span> valid_dl])</span><br><span class="line">        val_loss = np.sum(np.multiply(losses,nums)) / np.sum(nums)</span><br><span class="line"></span><br><span class="line">        print(epoch, val_loss)</span><br></pre></td></tr></table></figure>

<p>定义get_data()函数返回用于训练和验证集的dataloader。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">get_data</span><span class="params">(train_ds, valid_ds, bs)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> (DataLoader(train_ds, batch_size=bs, shuffle=<span class="literal">True</span>),</span><br><span class="line">            DataLoader(valid_ds, batch_size=bs*<span class="number">2</span>))</span><br></pre></td></tr></table></figure>

<p>现在，我们获取数据加载器并拟合模型的整个过程可以在3行代码中运行:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">train_dl,valid_dl = get_data(train_ds, valid_ds, bs)</span><br><span class="line">model,opt = get_model()</span><br><span class="line">fit(epochs, model, loss_func, opt, train_dl, valid_dl)</span><br></pre></td></tr></table></figure>

<p>您可以使用这三行代码来训练各种各样的模型。让我们看看是否可以用它们来训练一个卷积神经网络(CNN)!</p>
<h1 id="切换到CNN"><a href="#切换到CNN" class="headerlink" title="切换到CNN"></a>切换到CNN</h1><h2 id="第一次尝试"><a href="#第一次尝试" class="headerlink" title="第一次尝试"></a>第一次尝试</h2><p>我们现在要构建一个有三个卷积层的神经网络。因为前一节中的函数都没有假定任何关于模型形式的内容，所以我们可以使用它们来训练CNN，而无需进行任何修改。<br>我们将使用Pytorch预定义的Conv2d类作为卷积层。我们定义了一个3个卷积层的CNN。每个卷积后面都有一个ReLU。最后，我们执行一个平均池。(注意，view()方法是PyTorch版本的numpy reshape()方法)。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Mnist_CNN</span><span class="params">(nn.Module)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        super().__init__()</span><br><span class="line">        self.conv1 = nn.Conv2d(<span class="number">1</span>,  <span class="number">16</span>, kernel_size=<span class="number">3</span>, stride=<span class="number">2</span>, padding=<span class="number">1</span>)</span><br><span class="line">        self.conv2 = nn.Conv2d(<span class="number">16</span>, <span class="number">16</span>, kernel_size=<span class="number">3</span>, stride=<span class="number">2</span>, padding=<span class="number">1</span>)</span><br><span class="line">        self.conv3 = nn.Conv2d(<span class="number">16</span>, <span class="number">10</span>, kernel_size=<span class="number">3</span>, stride=<span class="number">2</span>, padding=<span class="number">1</span>)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">forward</span><span class="params">(self, xb)</span>:</span></span><br><span class="line">        xb = xb.view(<span class="number">-1</span>,<span class="number">1</span>,<span class="number">28</span>,<span class="number">28</span>)</span><br><span class="line">        xb = F.relu(self.conv1(xb))</span><br><span class="line">        xb = F.relu(self.conv2(xb))</span><br><span class="line">        xb = F.relu(self.conv3(xb))</span><br><span class="line">        xb = F.avg_pool2d(xb, <span class="number">4</span>)</span><br><span class="line">        <span class="keyword">return</span> xb.view(<span class="number">-1</span>,xb.size(<span class="number">1</span>))</span><br><span class="line"></span><br><span class="line">lr=<span class="number">0.1</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 动量是随机梯度下降的一种变化，它也考虑了以前的更新，通常会使训练更快的收敛。</span></span><br><span class="line">model = Mnist_CNN()</span><br><span class="line">opt = optim.SGD(model.parameters(), lr=lr, momentum=<span class="number">0.9</span>)</span><br><span class="line">fit(epochs, model, loss_func, opt, train_dl, valid_dl)</span><br></pre></td></tr></table></figure>

<h2 id="nn-Sequential"><a href="#nn-Sequential" class="headerlink" title="nn.Sequential"></a>nn.Sequential</h2><p>torch.nn还有一个方便的类，我们可以用它来简化代码:Sequential。Sequential对象以顺序的方式运行其中包含的每个模块。这是一种更简单的神经网络的写法。<br>为了利用这一点，我们需要能够从给定的函数轻松地定义一个自定义层。例如，PyTorch没有视图层，我们需要为我们的网络创建一个视图层。Lambda将创建一个层，然后我们可以使用它来定义一个具有序列的网络。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Lambda</span><span class="params">(nn.Module)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, func)</span>:</span></span><br><span class="line">        super().__init__()</span><br><span class="line">        self.func=func</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">forward</span><span class="params">(self, x)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> self.func(x)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">preprocess</span><span class="params">(x)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> x.view(<span class="number">-1</span>,<span class="number">1</span>,<span class="number">28</span>,<span class="number">28</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 使用‘Sequential’创建的模型很简单</span></span><br><span class="line">model = nn.Sequential(</span><br><span class="line">    Lambda(preprocess),</span><br><span class="line">    nn.Conv2d(<span class="number">1</span>,  <span class="number">16</span>, kernel_size=<span class="number">3</span>, stride=<span class="number">2</span>, padding=<span class="number">1</span>), nn.ReLU(),</span><br><span class="line">    nn.Conv2d(<span class="number">16</span>, <span class="number">16</span>, kernel_size=<span class="number">3</span>, stride=<span class="number">2</span>, padding=<span class="number">1</span>), nn.ReLU(),</span><br><span class="line">    nn.Conv2d(<span class="number">16</span>, <span class="number">10</span>, kernel_size=<span class="number">3</span>, stride=<span class="number">2</span>, padding=<span class="number">1</span>), nn.ReLU(),</span><br><span class="line">    nn.AvgPool2d(<span class="number">4</span>),</span><br><span class="line">    Lambda(<span class="keyword">lambda</span> x: x.view(x.size(<span class="number">0</span>),<span class="number">-1</span>))</span><br><span class="line">)</span><br><span class="line">opt = optim.SGD(model.parameters(), lr=lr, momentum=<span class="number">0.9</span>)</span><br><span class="line">fit(epochs, model, loss_func, opt, train_dl, valid_dl)</span><br></pre></td></tr></table></figure>

<h2 id="包装DataLoader"><a href="#包装DataLoader" class="headerlink" title="包装DataLoader"></a>包装DataLoader</h2><p>我们的CNN相当简洁，但它只适用于MNIST，因为:</p>
<ul>
<li>它假设输入是一个28*28长的向量</li>
<li>它假设最终的CNN网格大小是4*4(因为这是我们使用的平均池内核大小)</li>
</ul>
<p>让我们摆脱这两个假设，以便我们的模型适用于任何二维单通道图像。首先，我们可以删除初始Lambda层，但将数据预处理移动到生成器中:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">preprocess</span><span class="params">(x,y)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> x.view(<span class="number">-1</span>,<span class="number">1</span>,<span class="number">28</span>,<span class="number">28</span>),y</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">WrappedDataLoader</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, dl, func)</span>:</span></span><br><span class="line">        self.dl = dl</span><br><span class="line">        self.func = func</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__len__</span><span class="params">(self)</span>:</span> <span class="keyword">return</span> len(self.dl)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__iter__</span><span class="params">(self)</span>:</span></span><br><span class="line">        batches = iter(self.dl)</span><br><span class="line">        <span class="keyword">for</span> b <span class="keyword">in</span> batches: <span class="keyword">yield</span>(self.func(*b))</span><br><span class="line"></span><br><span class="line">train_dl,valid_dl = get_data(train_ds, valid_ds, bs)</span><br><span class="line">train_dl = WrappedDataLoader(train_dl, preprocess)</span><br><span class="line">valid_dl = WrappedDataLoader(valid_dl, preprocess)</span><br></pre></td></tr></table></figure>

<p>接下来，我们可以用nn.AdaptiveAvgPool2d替换nn.AvgPool2d，它允许我们定义我们想要的输出张量的大小，而不是我们拥有的输入张量。因此，我们的模型可以处理任何大小的输入。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">model = nn.Sequential(</span><br><span class="line">    nn.Conv2d(<span class="number">1</span>,  <span class="number">16</span>, kernel_size=<span class="number">3</span>, stride=<span class="number">2</span>, padding=<span class="number">1</span>), nn.ReLU(),</span><br><span class="line">    nn.Conv2d(<span class="number">16</span>, <span class="number">16</span>, kernel_size=<span class="number">3</span>, stride=<span class="number">2</span>, padding=<span class="number">1</span>), nn.ReLU(),</span><br><span class="line">    nn.Conv2d(<span class="number">16</span>, <span class="number">10</span>, kernel_size=<span class="number">3</span>, stride=<span class="number">2</span>, padding=<span class="number">1</span>), nn.ReLU(),</span><br><span class="line">    nn.AdaptiveAvgPool2d(<span class="number">1</span>),</span><br><span class="line">    Lambda(<span class="keyword">lambda</span> x: x.view(x.size(<span class="number">0</span>),<span class="number">-1</span>))</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line">opt = optim.SGD(model.parameters(), lr=lr, momentum=<span class="number">0.9</span>)</span><br><span class="line">fit(epochs, model, loss_func, opt, train_dl, valid_dl)</span><br></pre></td></tr></table></figure>

<h2 id="使用GPU"><a href="#使用GPU" class="headerlink" title="使用GPU"></a>使用GPU</h2><p>实际训练中稍微略大一点的项目，几乎不会有人使用CPU来训练，那样太慢了。首先查看一下你的GPU是否能在PyTorch下工作：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">torch.cuda.is_available()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 然后为它创建一个设备对象:</span></span><br><span class="line">dev = torch.device(<span class="string">'cuda'</span>) <span class="keyword">if</span> torch.cuda.is_available() \</span><br><span class="line">        <span class="keyword">else</span> torch.device(<span class="string">'cpu'</span>)</span><br></pre></td></tr></table></figure>

<p>让我们更新预处理函数preprocess()，将batches移动到GPU:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">preprocess</span><span class="params">(x,y)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> x.view(<span class="number">-1</span>,<span class="number">1</span>,<span class="number">28</span>,<span class="number">28</span>).to(dev),y.to(dev)</span><br><span class="line"></span><br><span class="line">train_dl,valid_dl = get_data(train_ds, valid_ds, bs)</span><br><span class="line">train_dl = WrappedDataLoader(train_dl, preprocess)</span><br><span class="line">valid_dl = WrappedDataLoader(valid_dl, preprocess)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 最后，我们可以将模型移动到GPU。</span></span><br><span class="line">model.to(dev)</span><br><span class="line">opt = optim.SGD(model.parameters(), lr=lr, momentum=<span class="number">0.9</span>)</span><br><span class="line">fit(epochs, model, loss_func, opt, train_dl, valid_dl)</span><br></pre></td></tr></table></figure>
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/11/04/Python的魔法方法-call/" rel="next" title="Python的魔法方法__call__()和__init__()拾遗">
                <i class="fa fa-chevron-left"></i> Python的魔法方法__call__()和__init__()拾遗
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="南林笑笑生">
            
              <p class="site-author-name" itemprop="name">南林笑笑生</p>
              <p class="site-description motion-element" itemprop="description">无论如何，人生是美丽的。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">8</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#神经网络初探"><span class="nav-number">1.</span> <span class="nav-text">神经网络初探</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#MNIST数据集设置"><span class="nav-number">1.1.</span> <span class="nav-text">MNIST数据集设置</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用optim重构"><span class="nav-number">1.2.</span> <span class="nav-text">使用optim重构</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用DataLoader来重构"><span class="nav-number">1.3.</span> <span class="nav-text">使用DataLoader来重构</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#重构一下拟合和获取数据的代码"><span class="nav-number">1.4.</span> <span class="nav-text">重构一下拟合和获取数据的代码</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#切换到CNN"><span class="nav-number">2.</span> <span class="nav-text">切换到CNN</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#第一次尝试"><span class="nav-number">2.1.</span> <span class="nav-text">第一次尝试</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#nn-Sequential"><span class="nav-number">2.2.</span> <span class="nav-text">nn.Sequential</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#包装DataLoader"><span class="nav-number">2.3.</span> <span class="nav-text">包装DataLoader</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用GPU"><span class="nav-number">2.4.</span> <span class="nav-text">使用GPU</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">南林笑笑生</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
